var sysResourceTable = function() {
	var validator;
	return {
		init : function() {
			var tableId = "sys_resource_table";
			util.initCheckBox(tableId);
			var checkBoxDivStr = '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"></span></div>';
			
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "resName",
					"value" : $("#query_resName").val().trim()
				});
				aoData.push({
					"name" : "resType",
					"value" : $("#query_resType").val()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			$('#sys_resource_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/sysResource/getResource.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return checkBoxDivStr;
					},
					"bSortable" : false
				},
				util.createRowIndex(),
				{
					"data" : "resName",
					"bSortable" : false,
					"defaultContent": ""
				}, {
					"data" : "resUrl",
					"bSortable" : false,
					"defaultContent": ""
				}, {
					"data" : "resSort",
					"bSortable" : false,
					"defaultContent": ""
				}],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});

			$('#sys_resource_table tbody').on('click', 'tr', function() {
				var table = $('#sys_resource_table').DataTable();
				if ($(this).hasClass('selected')) {
					$(this).removeClass('selected');
				} else {
					table.$('tr.selected').removeClass('selected');
					$(this).addClass('selected');
				}
			});
			
			jQuery('#sys_resource_table .group-checkable').change(function() {
				var set = jQuery(this).attr("data-set");
				var checked = jQuery(this).is(":checked");
				jQuery(set).each(function() {
					if (checked) {
						$($(this).parent()).attr("class", "checked");
					} else {
						$($(this).parent()).removeClass("checked");
					}
				});
				jQuery.uniform.update(set);
			});
			// 查询
			$("#btn_query").on("click", function(e) {
				var table = $('#sys_resource_table').DataTable();
				table.draw(true);
			});
		    // 重置
			$("#btn_reset").on("click", function(e) {
				$("#query_resName").val("");
				$("#query_resType").val("");
			});
			// 新增菜单
			$("#sys_resource_table_new").on("click", function(e) {
				$('#addResource_title').text('新增资源');
				createTree();
				util.getDictByParentKey("SYS_ZYLBDM", 'resType', '请选择');
				$("#add-resource").modal({show:true, keyboard:false});
			});
			
			// 修改
			$("#sys_resource_table_edit").on("click",function(e) {
				$('#addResource_title').text('编辑资源');
				var d = [];
				d = util.getCheckedData("sys_resource_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return;
				}
				$.ajax({
					"type" : "post",
					"url" : "main/sysResource/initEditResourceById.mvc",
					"dataType" : "json",
					"data" : {id:d[0].pkId},
					"success" : function(data) {
						var resource = data.resource;
						util.createOption("resType", "请选择", data.resTypeDict)
						$("#form_id").val(resource.pkId);
						$("#resName").val(resource.resName);
						$("#resType").val(resource.resType);
						$("#resUrl").val(resource.resUrl);
						$("#resSort").val(resource.resSort);
						$("#remark").val(resource.remark);
						//给树赋值
						var zNodes = data.resTree;  
		                $.fn.zTree.init($("#resTreeDemo"), setting, zNodes);
		                if (resource.parentId) {
		                	var treeObj = $.fn.zTree.getZTreeObj("resTreeDemo");
						    var node=treeObj.getNodeByParam("pkId",resource.parentId, null);
						    treeObj.selectNode(node,false);
						    $("#parentName").attr("value", node.resName);  
					        $("#parentId").attr("value", node.pkId);
		                }
						$("#add-resource").modal({show:true, keyboard:false});
					}
				});
			});
			
			//删除资源
			$("#sys_resource_table_del").on("click",function(e) {
				var d = [];
				d = util.getCheckedData("sys_resource_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return;
				} else {
					util.showModal("#_confirmModal", "您确定要删除选中的记录及子记录？", "_confirmModal_yes");
				}
			});
			
			//确认删除
			$("#_confirmModal").on('click', '#_confirmModal_yes', function() {
				var d = [];
				d = util.getCheckedData("sys_resource_table");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#sys_resource_table').DataTable();
				var selRows = table.rows('.selected');
				var selData = selRows.data();
				$.ajax({
					"type" : "post",
					"url" : "main/sysResource/delResource.mvc",
					"dataType" : "json",
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						selRows.remove();
						table.draw(true);
						rmsBox.notify('success', {msg: '删除成功！'});
					}
				});
			});
			
			// 新增资源 保存
			$("#form_resource_save").click(function(e) {
				validator = validateMyForm("resource_form");
				if(validator.form()){
					save();
				}else{
					return false;
				}
				
			});
			
			//关闭弹窗清空表单内容
			$("#form_btn_close").click(function(){
				$("#form_id").val("");
				$("#parentId").attr("value", "");
				$("#parentName").attr("value", "");
				$("#resource_form")[0].reset();
				if (validator) {
					validator.resetForm();
				}
			});
			
			//保存方法
			function save() {
				var d = {};
				var id = $("#form_id").val();
				var parentId = $("#parentId").val() == null || $("#parentId").val().length == 0 ? '' : $("#parentId").val();
				var resName = $("#resName").val();
				var resUrl = $("#resUrl").val();
				var resType = $("#resType").val();
				var resSort = $("#resSort").val();
				var remark = $("#remark").val();
				
				d['parentId'] = parentId;
				d['resName'] = resName;
				d['resUrl'] = resUrl;
				d['resType'] = resType;
				d['resSort'] = resSort;
				d['remark'] = remark;
				d['id'] = id;
				var table = $('#sys_resource_table').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/sysResource/saveOrUpdateSysResource.mvc",
					"dataType" : "json",
					"data" : {
						"record" : JSON.stringify(d)
					},
					"success" : function(resp) {
						if (resp.msg == 'parentId_error') {
							rmsBox.notify('error', {msg: '上级资源不能是当前资源的子资源！', delay: 3000, width: 360});
							return;
						} else if (resp.msg == 'error') {
							rmsBox.notify('error', {msg: '操作失败！',delay: 3000});
							return;
						} else if (resp.msg == 'duplicate') {
							rmsBox.notify('error', {msg: '资源名称或资源URL已存在！', delay: 3000, width: 320});
							return;
						} 
						rmsBox.notify('success', {msg: '操作成功！'});
						$("#form_btn_close").click();
						table.draw(true);
					}
				});
			};
			

			//validate 自定义验证
			function validateMyForm(formId){
				return $( '#' + formId ).validate({  
					errorElement: 'em',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	resName:'required',
			        	resType:'required',
			        	resUrl:'required',
			        	resSort:{'required':true,'checkSort':true}
			            },  
			        messages:{  
			        	resName:'不能为空',
			        	resType:'不能为空',
			        	resUrl:'不能为空',
			        	resSort:{required:'不能为空',checkSort:'值在1-9999之间'}
			            }, 
			            errorPlacement: function (error, element) { 
			            	//默认以span形式显示在输入框后
		                   error.insertAfter(element);
		                   $(element.next()).attr('title', $(error).text()).tooltip();
		                   $(error).text('');
		                }
			    });  
			};
			$.validator.addMethod("checkSort",function(value,element,params){  
	            var checkSort = /^[1-9]{1,4}$/;  
	            return this.optional(element)||(checkSort.test(value));  
	        });
			$(function(){
				$('.search-body input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_query').click();
					}
				});
			});
		}
	};
}();
/******************资源树 resourceTree 开始******************************/
function showMenu() {  
    var nameObj = $("#parentName");  
    var nameOffset = $("#parentName").offset(); 
    //计算 没计算好
    $("#resContent").css({ left: 99 + "px", top: 27 + "px" }).slideDown("fast");  

    $("body").bind("mousedown", onBodyDown);  
} 

var setting = {  
    view: {  
        showLine: false,  
        dblClickExpand: true  
    },  
    data: {  
        key : {
            name: "resName"
        },
        simpleData: {
            enable: true,  
            idKey: "pkId",  
            pIdKey: "parentId",  
            rootPId: "0"
        }  
    },  
    callback: {  
        beforeClick: beforeClick,  
        onClick: onClick  
    }  
};  

function createTree() {  
    var zNodes;  
    $.ajax({  
        type: 'POST',  
        url: "main/sysResource/getResourceTree.mvc", //url    
        data: { id: "0" },  
        dataType: "json",   //可以是text，如果用text，返回的结果为字符串；如果需要json格式的，可是设置为json  
        ContentType: "application/json; charset=utf-8",  
        success: function (data) {  
            zNodes = data.aaData;  
            $.fn.zTree.init($("#resTreeDemo"), setting, zNodes);  
        },  
        error: function (msg) {  
            console.info('获取树失败');
        }  
    }); 
}  

// 控制父节点不显示图标  
function showIconForTree(treeId, treeNode) {  
    return !treeNode.isParent;  
};  

	
function beforeClick(treeId, treeNode) { 
  	return true;  
}  

function onClick(e, treeId, treeNode) {  
    var zTree = $.fn.zTree.getZTreeObj("resTreeDemo"),  
    nodes = zTree.getSelectedNodes(); 
    $("#parentName").attr("value", nodes[0].resName);  
    $("#parentId").attr("value", nodes[0].pkId);
    hideMenu();
}  

function hideMenu() {  
    $("#resContent").fadeOut("fast");  
    $("body").unbind("mousedown", onBodyDown);  
}  
// 当点击窗口其他区域时zTree消息框隐藏  
function onBodyDown(event) {  
    if (!(event.target.id == "menuBtn" || event.target.id == "resContent" || $(event.target).parents("#resContent").length > 0)) {  
        hideMenu();  
    }  
}  
   /******************资源树 resourceTree 结束******************************/